<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;

class Community extends Common
{
	
	function community($val,$pagesize=12)
	{
		//$where = array();
		$where['Pid'] = ['=',0];
    	$order='Addtime desc';
		$State = input('get.State');
        $StarAddTime= input('get.StarAddTime');
        $EndAddTime = input('get.EndAddTime');
    	$Uname = input('get.Uname');
    	if($Uname){
    		$ids = model('User')->queryUserIds($Uname);
    		$where['User_id'] = ['in',$ids];
    	}
		if($StarAddTime || $EndAddTime){
            if(strtotime($EndAddTime)<strtotime($StarAddTime)){
                return '<script>alert("请选择正确的时间"),history.go(-1)</script>';
            }       
			$where['Addtime'] =array(['>=',strtotime($StarAddTime)],['<=',strtotime($EndAddTime)]);
        }
        if($State){
        	$where['State']=['=',$State];
        }
		$arr = [
			'val'=>$val,
			'Uname'=>$Uname,
			'State'=>$State,			
			'StarAddTime'=>$StarAddTime,
			'EndAddTime'=>$EndAddTime,
		];
		$pageListr = Db::name($val)->where($where)->order($order)->paginate($pagesize,false,['query'=>$arr]);
		//$community_list = getCommunityReplyInfinite($pageListr->all());
		$community_list = $pageListr->all();
		foreach($community_list as $k => $v){
			$community_list[$k]['Rply'] = getCommunityReplyList($v['id'],$val);
		}
		$arr['pageListr'] = $pageListr;
		$arr['community_list'] = $community_list;
		return view('index',$arr);
	}
	public function deleteCommunity($id,$val)
	{
		if (!$this->REQUEST->isAjax()) return "非法操作";
		$vn = Db::name($val)->field('id,Pid')->select();
		$vm = Db::name($val)->where('id','in',$id)->field('id,Pid')->select();
		$ids = array();
		foreach($vm as $v=>$m){
			$t = getAllCategoryChild($vn,$m['id']);
			if(is_array($t))
			$ids = array_unique(array_merge($ids,$t));
			$ids[] = $m['id'];
		};
		$ids = implode(',',$ids);
		$where['id'] = ['in',$ids];
		if(Db::name($val)->where($where)->delete());
		return json(['code'=>1,'msg'=>'删除成功']);
   		return json(['code'=>0,'msg'=>'删除失败']);
	}
	public function toexamineCommunity($id,$sta,$val)
	{
		if (!$this->REQUEST->isAjax()) return "非法操作";
		$where['id'] = ['in',$id];
		if(Db::name($val)->where($where)->setField('State',$sta));
		return json(['code'=>1,'msg'=>'更新成功']);
   		return json(['code'=>0,'msg'=>'更新失败']);
	}
	//評論列表
    function seerCommunityRply($id,$val){
       	if( !$this->REQUEST->isAjax() ) return '非法操作';
	   	if($data = getCommunityReplyList($id,$val))
	   	return json(['code'=>1,'msg'=>'读取成功','data'=>$data]);
   		return json(['code'=>0,'msg'=>'暂无评论']);
    }

	public function message()
	{
		return $this->community('message');
	}
	public function feedback()
	{
		return $this->community('feedback');
	}
	
}
